package com.linxianqin.springbootVue.service.webService;

import com.linxianqin.springbootVue.domain.dto.SysUserDTO;
import com.linxianqin.springbootVue.domain.model.LoginUser;
import com.linxianqin.springbootVue.domain.enums.UserStatus;
import com.linxianqin.springbootVue.manage.exception.BaseException;
import com.linxianqin.springbootVue.service.SysUserService;
import com.linxianqin.springbootVue.utils.text.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 功能描述：加载用户信息
 * @author lxq
 * @version 1.00
 * @Date 2020/12/12
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private SysUserService sysUserService;
    private SysPermissionService permissionService;
    public UserDetailsServiceImpl(SysUserService sysUserService,SysPermissionService permissionService){
        this.sysUserService=sysUserService;
        this.permissionService=permissionService;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDTO userDTO = sysUserService.selectUserByUserName(username);
        if (StringUtils.isNull(userDTO))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(userDTO.getDeleted()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(userDTO.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        return createLoginUser(userDTO);
    }
    public UserDetails createLoginUser(SysUserDTO userDTO)
    {
       return new LoginUser(userDTO, permissionService.getMenuPermission(userDTO));
    }
}
